package cn.xc.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("/login")||uri.endsWith("/register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        String token = request.getHeader("token");
        response.setContentType("application/json;charset=utf-8");
        if (!StringUtils.isEmpty(token)){
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","登录失效，请重新登录!");
            String strMap = JSON.toJSONString(map);

            try {
                response.getWriter().print(strMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }

        return null;
    }
}
